{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import absolute_import\n",
    "from __future__ import division\n",
    "from __future__ import print_function\n",
    "\n",
    "import tensorflow as tf\n",
    "\n",
    "slim = tf.contrib.slim"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def trunc_normal(stddev): return tf.truncated_normal_initializer(stddev=stddev)\n",
    "\n",
    "\n",
    "def bn_act_conv_drp(current, num_outputs, kernel_size, scope='block'):\n",
    "    current = slim.batch_norm(current, scope=scope + '_bn')\n",
    "    current = tf.nn.relu(current)\n",
    "    current = slim.conv2d(current, num_outputs, kernel_size, scope=scope + '_conv')\n",
    "    current = slim.dropout(current, scope=scope + '_dropout')\n",
    "    return current\n",
    "\n",
    "\n",
    "def block(net, layers, growth, scope='block'):\n",
    "    for idx in range(layers):\n",
    "        bottleneck = bn_act_conv_drp(net, 4 * growth, [1, 1],\n",
    "                                     scope=scope + '_conv1x1' + str(idx))\n",
    "        tmp = bn_act_conv_drp(bottleneck, growth, [3, 3],\n",
    "                              scope=scope + '_conv3x3' + str(idx))\n",
    "        net = tf.concat(axis=3, values=[net, tmp])\n",
    "    return net"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 过渡层\n",
    "def transition(current,outPutSize,scope='transition'):\n",
    "    current = slim.batch_norm(current, scope=scope + '_bn')\n",
    "    current = slim.conv2d(current, outPutSize, [1,1], scope=scope + '_conv1x1')\n",
    "    current = slim.avg_pool2d(current, [2,2],stride=[2, 2], padding='VALID', scope=scope + '_pool2x2')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def bn_drp_scope(is_training=True, keep_prob=0.8):\n",
    "    keep_prob = keep_prob if is_training else 1\n",
    "    with slim.arg_scope(\n",
    "        [slim.batch_norm],\n",
    "            scale=True, is_training=is_training, updates_collections=None):\n",
    "        with slim.arg_scope(\n",
    "            [slim.dropout],\n",
    "                is_training=is_training, keep_prob=keep_prob) as bsc:\n",
    "            return bsc\n",
    "\n",
    "\n",
    "def densenet_arg_scope(weight_decay=0.004):\n",
    "    \"\"\"Defines the default densenet argument scope.\n",
    "\n",
    "    Args:\n",
    "      weight_decay: The weight decay to use for regularizing the model.\n",
    "\n",
    "    Returns:\n",
    "      An `arg_scope` to use for the inception v3 model.\n",
    "    \"\"\"\n",
    "    with slim.arg_scope(\n",
    "        [slim.conv2d],\n",
    "        weights_initializer=tf.contrib.layers.variance_scaling_initializer(\n",
    "            factor=2.0, mode='FAN_IN', uniform=False),\n",
    "        activation_fn=None, biases_initializer=None, padding='same',\n",
    "            stride=1) as sc:\n",
    "        return sc"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def densenet(images, num_classes=1001, is_training=False,\n",
    "             dropout_keep_prob=0.8,\n",
    "             scope='densenet'):\n",
    "    \"\"\"Creates a variant of the densenet model.\n",
    "\n",
    "      images: A batch of `Tensors` of size [batch_size, height, width, channels].\n",
    "      num_classes: the number of classes in the dataset.\n",
    "      is_training: specifies whether or not we're currently training the model.\n",
    "        This variable will determine the behaviour of the dropout layer.\n",
    "      dropout_keep_prob: the percentage of activation values that are retained.\n",
    "      prediction_fn: a function to get predictions out of logits.\n",
    "      scope: Optional variable_scope.\n",
    "\n",
    "    Returns:\n",
    "      logits: the pre-softmax activations, a tensor of size\n",
    "        [batch_size, `num_classes`]\n",
    "      end_points: a dictionary from components of the network to the corresponding\n",
    "        activation.\n",
    "    \"\"\"\n",
    "    growth = 24\n",
    "    compression_rate = 0.5\n",
    "\n",
    "    def reduce_dim(input_feature):\n",
    "        return int(int(input_feature.shape[-1]) * compression_rate)\n",
    "\n",
    "    end_points = {}\n",
    "\n",
    "    with tf.variable_scope(scope, 'DenseNet', [images, num_classes]):\n",
    "        with slim.arg_scope(bn_drp_scope(is_training=is_training,\n",
    "                                         keep_prob=dropout_keep_prob)) as ssc:\n",
    "            #pass\n",
    "            ##########################\n",
    "            # Put your code here.\n",
    "            ##########################\n",
    "            \n",
    "            # 先是2k的feature-maps输出，只有第一次是2k，其他都是k\n",
    "            densnet = slim.conv2d(images, 2*growth, [7,7], [2,2], scope=scope + '_conv7x7')\n",
    "            densnet = slim.max_pool2d(densnet, [3,3], stride=[2,2], padding='VALID', scope=scope + '_pool3x3')\n",
    "            \n",
    "            # 第一个dense block\n",
    "            densnet = block(densnet, 6, growth, scope='block1')\n",
    "            # 第一个transition layer\n",
    "            densnet = transition(densnet, reduce_dim(densnet), scope='transition1')\n",
    "            \n",
    "            # 第二个dense block\n",
    "            densnet = block(densnet, 12, growth, scope='block2')\n",
    "            # 第二个transition layer\n",
    "            densnet = transition(densnet, reduce_dim(densnet), scope='transition2')\n",
    "            \n",
    "            # 第三个dense block ，根据Densnet-264设置\n",
    "            densnet = block(densnet, 64, growth, scope='block3')\n",
    "            # 第三个transition layer\n",
    "            densnet = transition(densnet, reduce_dim(densnet), scope='transition3')\n",
    "            \n",
    "            # 第四个dense block ，根据Densnet-264设置\n",
    "            densnet = block(densnet, 48, growth, scope='block4')\n",
    "            \n",
    "            # 全局平均池化，输出就是7 x 7的，所以用7 x 7 大小的平均池化，即全局平均池化\n",
    "            densnet = slim.avg_pool2d(densnet, [7,7], padding='VALID', scope=scope + '_pool7x7')\n",
    "            \n",
    "            densnet = slim.flatten(densnet, scope=scope + '_flatten')\n",
    "            #end_points['PreLogitsFlatten'] = densnet\n",
    "\n",
    "            logits = slim.fully_connected(densnet, num_classes, activation_fn=None, scope=scope + '_logits')\n",
    "            #end_points['Logits'] = logits\n",
    "            \n",
    "            end_points['Predictions'] = tf.nn.softmax(logits, name='Predictions')\n",
    "    return logits, end_points"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "densenet.default_image_size = 224\n",
    "\n",
    "# 调用densnet网络训练？？\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
